package cn.aicnn.chatssespringboot.service.Impl;

import cn.aicnn.chatssespringboot.common.CommonResponse;
import cn.aicnn.chatssespringboot.service.ChatService;
import cn.aicnn.chatssespringboot.service.DialogService;
import cn.aicnn.chatssespringboot.service.NewChatService;
import cn.aicnn.chatssespringboot.vo.ChatVO;
import org.apache.log4j.Logger;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

@Service
public class NewChatServiceImpl implements NewChatService {
    private static final Logger logger = Logger.getLogger(NewChatServiceImpl.class);

    @Autowired
    ChatService chatService;
    @Autowired
    DialogService dialogService;

    @Override
    public ChatVO newChat(String username, String question) {
        ChatVO chatVO = new ChatVO();
        ChatVO.NewAnswer newAnswer = new ChatVO.NewAnswer();
        String answer = useModel(question);
        logger.info("answer:" + answer);
        int chatId = chatService.insertChat(question, username);
        int dialogId = dialogService.insertTextDialog(chatId, question, answer);
        chatVO.setChatName(question);
        chatVO.setChatid(chatId);
        newAnswer.setId(0);
        newAnswer.setText(answer);
        chatVO.setNewAnswer(newAnswer);
        return chatVO;
    }

    public String useModel(String question) {
        String pythonScriptPath = "G:\\大三上实训\\text.py";
        String userInput = question; // 你想传递的字符串
        ProcessBuilder processBuilder = new ProcessBuilder("python", pythonScriptPath);
        // 如果需要激活conda环境，使用以下代码代替上面的ProcessBuilder
        // ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c",
        //        "conda activate ame && python " + pythonScriptPath);

        try {
            // 启动进程
            Process process = processBuilder.start();

            OutputStream os = process.getOutputStream();
            os.write((userInput + "\n").getBytes()); // 发送输入并换行
            os.flush(); // 刷新输出流
            os.close(); // 关闭输出流

            // 创建线程来读取标准输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder output = new StringBuilder();
            new Thread(() -> {
                String line;
                try {
                    while ((line = reader.readLine()) != null) {
                        output.append(line).append("\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

            // 创建线程来读取错误输出
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            StringBuilder errorOutput = new StringBuilder();
            new Thread(() -> {
                String line;
                try {
                    while ((line = errorReader.readLine()) != null) {
                        errorOutput.append(line).append("\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

            // 等待进程结束并获取退出值
            int exitCode = process.waitFor();
            System.out.println("Python脚本输出:\n" + output.toString());
            System.out.println("错误输出:\n" + errorOutput.toString());
            System.out.println("退出代码: " + exitCode);

            return output.toString(); // 返回Python脚本的标准输出

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public CommonResponse<Object> userModel1(){
        useModel("");
        return CommonResponse.createForSuccess();
    }
}
